<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import io from 'socket.io-client'
import type { Socket } from 'socket.io-client'
import { nextTick, onMounted, onUnmounted, provide, ref } from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { Message } from '@/types/room'
import { getOrederDetailAPI } from '@/services/consult'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { MsgType, OrderType } from '@/enums'
import { showToast } from 'vant'
import dayjs from 'dayjs'

const store = useUserStore()
const route = useRoute()
const list = ref<Message[]>([])

const nextTime = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const finished = ref(false)
const loading = ref(false)
const onRefresh = () => {
  socket.emit('getChatMsgList', 20, nextTime.value, route.query.orderId as string)
}

let socket: Socket
onMounted(() => {
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.userInfo?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })

  socket.on('connect', () => {
    console.log('  -----> 欢迎光临 ')
  })

  socket.on('chatMsgList', ({ data }) => {
    loading.value = false
    if (!data.length) {
      finished.value = true
      return showToast('没有更多数据了')
    }

    nextTime.value = data[0].items[0].createTime

    if (!list.value.length) {
      list.value = data[0].items

      nextTick(() => {
        window.scrollTo({ top: document.body.scrollHeight })
      })
    } else {
      list.value.unshift(...data[0].items)
    }
  })

  socket.on('statusChange', loadOrderDetail)

  socket.on('receiveChatMsg', (data) => {
    console.log('data  ----->  ', data)
    list.value.push(data)

    nextTick(() => {
      window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' })
    })
  })
})

const orderDetail = ref<ConsultOrderItem>()
const loadOrderDetail = async () => {
  const res = await getOrederDetailAPI(route.query.orderId as string)
  orderDetail.value = res.data
}

onMounted(loadOrderDetail)
onUnmounted(() => {
  socket.close()
})

const onSendText = (text: string) => {
  socket.emit('sendChatMsg', {
    from: store.userInfo!.id,
    to: orderDetail.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}

const onSendImage = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.userInfo!.id,
    to: orderDetail.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: img
    }
  })
}

/** 更新消息列表 */
const updateEva = (score: number) => {
  // 5.
  console.log('我收到了子组件传来的soore，,我准备跟心数据  ----->  ')
  const preEvaItem = list.value.find((item) => {
    return item.msgType === MsgType.CardEvaForm
  })

  preEvaItem!.msg.evaluateDoc = {
    score
  }
  preEvaItem!.msgType = MsgType.CardEva

  console.log('preEveItem  ----->  ', preEvaItem)
}

provide('orderDetail', orderDetail)
// 3. 跨组件通信， 父组件，传递回调函数
provide('updateEva', updateEva)
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />

    <room-status :countDown="orderDetail?.countdown" :status="orderDetail?.status" />

    <van-pull-refresh v-model="loading" @refresh="onRefresh" :disabled="finished">
      <room-message :list="list" />
    </van-pull-refresh>
    <room-action
      :disabled="orderDetail?.status !== OrderType.ConsultChat"
      @send-text="onSendText"
      @send-image="onSendImage"
    />
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
